package com.wxyzz.cem.service;

import cn.hutool.core.lang.UUID;
import com.wxyzz.cem.exception.ImageServiceException;
import com.wxyzz.cem.service.interfaces.FileHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author xclhove
 */
@Service
@Slf4j
public class ImageService implements FileHandler {
    @Value("${image.path:./.idea/images}")
    private String imagePath;
    @Override
    public String upload(MultipartFile file) {
        // 获取原文件名
        String originalFilename = file.getOriginalFilename();
        // 获取文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 生成新的文件名
        String uuid = UUID.randomUUID().toString();
        String newFilename = uuid + suffix;
        
        // 设置文件保存的路径
        Path uploadPath = Paths.get(imagePath);
        
        try {
            if (!Files.exists(uploadPath)) {
                Files.createDirectory(uploadPath);
            }
            // 将文件保存到本地
            Files.copy(file.getInputStream(), uploadPath.resolve(newFilename));
            return newFilename;
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
            throw new ImageServiceException("上传图片失败！");
        }
    }
    
    @Override
    public File download(String fileName) {
        File file = new File(Paths.get(imagePath).resolve(fileName).toString());
        if (!file.exists()) {
            throw new ImageServiceException("图片不存在！");
        }
        return file;
    }
}
